import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Space, 
  Tag, 
  message, 
  Input, 
  Form, 
  Switch, 
  InputNumber,
  Select,
  Modal,
  Tabs,
  Row,
  Col,
  List,
  Empty,
  Popconfirm,
  Divider,
  Tooltip,
  Layout,
  Badge,
  Checkbox
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  SaveOutlined,
  ReloadOutlined,
  SettingOutlined,
  DatabaseOutlined,
  FormOutlined,
  SearchOutlined,
  TableOutlined,
  CopyOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined
} from '@ant-design/icons';
import { tableConfigApi, type TableConfigRecord } from '@/api/tableConfig';
import FieldEditor, { FIELD_TYPES } from './FieldEditor';

const { TabPane } = Tabs;
const { TextArea } = Input;
const { Option } = Select;
const { Sider, Content } = Layout;
const { Search } = Input;

const TableConfigManagement: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [tableList, setTableList] = useState<TableConfigRecord[]>([]);
  const [selectedTable, setSelectedTable] = useState<TableConfigRecord | null>(null);
  const [editingField, setEditingField] = useState<any>(null);
  const [fieldModalVisible, setFieldModalVisible] = useState(false);
  const [tableModalVisible, setTableModalVisible] = useState(false);
  const [editingTable, setEditingTable] = useState<TableConfigRecord | null>(null);
  const [activeTab, setActiveTab] = useState('fields');
  const [searchText, setSearchText] = useState('');

  const [form] = Form.useForm();

  // 获取表格列表
  const fetchTableList = async () => {
    setLoading(true);
    try {
      const response = await tableConfigApi.getList({ page: 1, pageSize: 100 });
      if (response.data.success && response.data.data) {
        setTableList(response.data.data);
        // 如果当前有选中的表格，更新它的数据
        if (selectedTable) {
          const updated = response.data.data.find((t: TableConfigRecord) => t.id === selectedTable.id);
          if (updated) {
            setSelectedTable(updated);
          }
        }
      }
    } catch (error) {
      message.error('获取表格列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTableList();
  }, []);

  // 选择表格
  const handleSelectTable = (table: TableConfigRecord) => {
    setSelectedTable(table);
    setActiveTab('fields');
  };

  // 新增表格
  const handleAddTable = () => {
    setEditingTable(null);
    form.resetFields();
    setTableModalVisible(true);
  };

  // 编辑表格
  const handleEditTable = (table: TableConfigRecord) => {
    setEditingTable(table);
    form.setFieldsValue({
      code: table.code,
      name: table.name,
      description: table.description,
      tableName: table.tableName,
      apiPath: table.apiPath,
      status: table.status,
      ...table.actions,
      ...table.tableProps,
    });
    setTableModalVisible(true);
  };

  // 保存表格
  const handleSaveTable = async () => {
    try {
      const values = await form.validateFields();
      
      const tableData: Partial<TableConfigRecord> = {
        code: values.code,
        name: values.name,
        description: values.description,
        tableName: values.tableName,
        apiPath: values.apiPath,
        status: values.status,
        actions: {
          create: values.create,
          update: values.update,
          delete: values.delete,
          batchDelete: values.batchDelete,
          export: values.export,
          import: values.import,
        },
        tableProps: {
          size: values.size || 'middle',
          rowKey: values.rowKey || 'id',
          bordered: values.bordered,
          pagination: {
            pageSize: values.pageSize || 10,
            showSizeChanger: true,
            showQuickJumper: true,
          },
          rowSelection: values.rowSelection,
        },
      };

      if (editingTable) {
        // 更新
        const response = await tableConfigApi.update(editingTable.id, { 
          ...editingTable, 
          ...tableData 
        });
        if (response.data.success) {
          message.success('更新成功');
          setTableModalVisible(false);
          fetchTableList();
        }
      } else {
        // 创建 - 初始化空字段数组
        const response = await tableConfigApi.create({
          ...tableData,
          fields: []
        });
        if (response.data.success) {
          message.success('创建成功');
          setTableModalVisible(false);
          fetchTableList();
        }
      }
    } catch (error) {
      console.error(error);
    }
  };

  // 删除表格
  const handleDeleteTable = async (table: TableConfigRecord) => {
    try {
      const response = await tableConfigApi.delete(table.id);
      if (response.data.success) {
        message.success('删除成功');
        if (selectedTable?.id === table.id) {
          setSelectedTable(null);
        }
        fetchTableList();
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 新增/编辑字段
  const handleEditField = (field?: any, index?: number) => {
    if (field) {
      setEditingField({ ...field, index });
    } else {
      setEditingField(null);
    }
    setFieldModalVisible(true);
  };

  // 保存字段
  const handleSaveField = async (fieldData: any) => {
    if (selectedTable) {
      const fields = [...(selectedTable.fields || [])];
      
      if (editingField?.index !== undefined) {
        // 更新字段
        fields[editingField.index] = fieldData;
      } else {
        // 新增字段
        fields.push(fieldData);
      }

      // 更新表格配置
      const response = await tableConfigApi.update(selectedTable.id, {
        ...selectedTable,
        fields,
      });

      if (response.data.success) {
        message.success('保存成功');
        setFieldModalVisible(false);
        setEditingField(null);
        fetchTableList();
      }
    }
  };

  // 删除字段
  const handleDeleteField = async (index: number) => {
    if (selectedTable) {
      const fields = [...(selectedTable.fields || [])];
      fields.splice(index, 1);

      const response = await tableConfigApi.update(selectedTable.id, {
        ...selectedTable,
        fields,
      });

      if (response.data.success) {
        message.success('删除成功');
        fetchTableList();
      }
    }
  };

  // 移动字段
  const handleMoveField = async (index: number, direction: 'up' | 'down') => {
    if (selectedTable) {
      const fields = [...(selectedTable.fields || [])];
      const newIndex = direction === 'up' ? index - 1 : index + 1;
      
      if (newIndex >= 0 && newIndex < fields.length) {
        [fields[index], fields[newIndex]] = [fields[newIndex], fields[index]];
        
        const response = await tableConfigApi.update(selectedTable.id, {
          ...selectedTable,
          fields,
        });

        if (response.data.success) {
          fetchTableList();
        }
      }
    }
  };

  // 复制表格
  const handleCopyTable = async (table: TableConfigRecord) => {
    const newTable: any = {
      ...table,
      code: `${table.code}_copy`,
      name: `${table.name}_副本`,
    };
    
    delete newTable.id;
    delete newTable.createdAt;
    delete newTable.updatedAt;
    delete newTable.tenantId;
    delete newTable.createdBy;
    delete newTable.updatedBy;
    
    try {
      const response = await tableConfigApi.create(newTable);
      if (response.data.success) {
        message.success('复制成功');
        fetchTableList();
      }
    } catch (error) {
      message.error('复制失败');
    }
  };

  // 表格列定义
  const tableColumns: ColumnsType<TableConfigRecord> = [
    {
      title: '表格名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: TableConfigRecord) => (
        <Space>
          {text}
          {record.status ? (
            <Badge status="success" />
          ) : (
            <Badge status="default" />
          )}
        </Space>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: any, record: TableConfigRecord) => (
        <Space size={0}>
          <Tooltip title="编辑">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                handleEditTable(record);
              }}
            />
          </Tooltip>
          <Tooltip title="复制">
            <Button
              type="link"
              size="small"
              icon={<CopyOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                handleCopyTable(record);
              }}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Popconfirm
              title="确定要删除这个表格配置吗？"
              onConfirm={(e) => {
                e?.stopPropagation();
                handleDeleteTable(record);
              }}
            >
              <Button
                type="link"
                size="small"
                danger
                icon={<DeleteOutlined />}
                onClick={(e) => e.stopPropagation()}
              />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 过滤后的表格列表
  const filteredTableList = tableList.filter(
    (table) => 
      table.name.toLowerCase().includes(searchText.toLowerCase()) ||
      table.code.toLowerCase().includes(searchText.toLowerCase())
  );

  return (
    <Layout style={{ height: 'calc(100vh - 120px)' }}>
      {/* 左侧表格列表 */}
      <Sider width={300} theme="light" style={{ borderRight: '1px solid #f0f0f0' }}>
        <div style={{ padding: 16 }}>
          <Space direction="vertical" style={{ width: '100%' }}>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              block
              onClick={handleAddTable}
            >
              新增表格
            </Button>
            <Search
              placeholder="搜索表格"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              allowClear
            />
          </Space>
        </div>
        
        <div style={{ padding: '0 16px', height: 'calc(100% - 120px)', overflowY: 'auto' }}>
          <Table
            dataSource={filteredTableList}
            columns={tableColumns}
            rowKey="id"
            pagination={false}
            size="small"
            loading={loading}
            onRow={(record) => ({
              onClick: () => handleSelectTable(record),
              style: {
                cursor: 'pointer',
                background: selectedTable?.id === record.id ? '#e6f7ff' : undefined,
              },
            })}
          />
        </div>
      </Sider>

      {/* 右侧配置面板 */}
      <Content style={{ background: '#fff' }}>
        {selectedTable ? (
          <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
            {/* 表格信息头部 */}
            <div style={{ padding: 16, borderBottom: '1px solid #f0f0f0' }}>
              <Row align="middle">
                <Col flex="1">
                  <Space>
                    <DatabaseOutlined style={{ fontSize: 20 }} />
                    <span style={{ fontSize: 16, fontWeight: 'bold' }}>
                      {selectedTable.name}
                    </span>
                    <Tag color="blue">{selectedTable.code}</Tag>
                    {selectedTable.status ? (
                      <Tag color="success">已启用</Tag>
                    ) : (
                      <Tag>已禁用</Tag>
                    )}
                  </Space>
                  {selectedTable.description && (
                    <div style={{ marginTop: 8, color: '#666' }}>
                      {selectedTable.description}
                    </div>
                  )}
                </Col>
                <Col>
                  <Space>
                    <Button
                      icon={<EditOutlined />}
                      onClick={() => handleEditTable(selectedTable)}
                    >
                      编辑表格
                    </Button>
                    <Button
                      icon={<ReloadOutlined />}
                      onClick={fetchTableList}
                    >
                      刷新
                    </Button>
                  </Space>
                </Col>
              </Row>
            </div>

            {/* 配置标签页 */}
            <div style={{ flex: 1, overflow: 'auto' }}>
              <Tabs
                activeKey={activeTab}
                onChange={setActiveTab}
                style={{ height: '100%' }}
                tabBarStyle={{ paddingLeft: 16 }}
              >
                <TabPane tab="字段配置" key="fields">
                  <div style={{ padding: 16 }}>
                    <Space direction="vertical" style={{ width: '100%' }} size="large">
                      <Button
                        type="dashed"
                        icon={<PlusOutlined />}
                        block
                        onClick={() => handleEditField()}
                      >
                        添加字段
                      </Button>
                      
                      {selectedTable.fields && selectedTable.fields.length > 0 ? (
                        <List
                          dataSource={selectedTable.fields}
                          renderItem={(field: any, index: number) => (
                            <List.Item
                              actions={[
                                <Button
                                  type="link"
                                  size="small"
                                  icon={<ArrowUpOutlined />}
                                  disabled={index === 0}
                                  onClick={() => handleMoveField(index, 'up')}
                                />,
                                <Button
                                  type="link"
                                  size="small"
                                  icon={<ArrowDownOutlined />}
                                  disabled={index === selectedTable.fields.length - 1}
                                  onClick={() => handleMoveField(index, 'down')}
                                />,
                                <Button
                                  type="link"
                                  size="small"
                                  icon={<EditOutlined />}
                                  onClick={() => handleEditField(field, index)}
                                />,
                                <Popconfirm
                                  title="确定删除此字段？"
                                  onConfirm={() => handleDeleteField(index)}
                                >
                                  <Button
                                    type="link"
                                    size="small"
                                    danger
                                    icon={<DeleteOutlined />}
                                  />
                                </Popconfirm>,
                              ]}
                            >
                              <List.Item.Meta
                                title={
                                  <Space>
                                    <span>{field.label}</span>
                                    <Tag color="blue">{field.key}</Tag>
                                    <Tag>{FIELD_TYPES.find(t => t.value === field.type)?.label || field.type}</Tag>
                                  </Space>
                                }
                                description={
                                  <Space size="small" wrap>
                                    {field.table?.hidden && <Tag color="default">隐藏</Tag>}
                                    {field.table?.sortable && <Tag color="green">可排序</Tag>}
                                    {field.search?.searchable && <Tag color="blue">可搜索</Tag>}
                                    {field.search?.quickSearch && <Tag color="cyan">快速搜索</Tag>}
                                    {field.form?.creatable && <Tag color="orange">可创建</Tag>}
                                    {field.form?.editable && <Tag color="purple">可编辑</Tag>}
                                  </Space>
                                }
                              />
                            </List.Item>
                          )}
                        />
                      ) : (
                        <Empty description="暂无字段配置" />
                      )}
                    </Space>
                  </div>
                </TabPane>

                <TabPane tab="表格设置" key="table">
                  <div style={{ padding: 16 }}>
                    <Card title="基本信息">
                      <Row gutter={[16, 16]}>
                        <Col span={12}>
                          <div>表名：{selectedTable.tableName}</div>
                        </Col>
                        <Col span={12}>
                          <div>API路径：{selectedTable.apiPath || '-'}</div>
                        </Col>
                      </Row>
                    </Card>

                    <Card title="功能开关" style={{ marginTop: 16 }}>
                      <Row gutter={[16, 16]}>
                        <Col span={8}>
                          <Space>
                            {selectedTable.actions?.create ? 
                              <CheckCircleOutlined style={{ color: '#52c41a' }} /> : 
                              <CloseCircleOutlined style={{ color: '#ccc' }} />
                            }
                            新增功能
                          </Space>
                        </Col>
                        <Col span={8}>
                          <Space>
                            {selectedTable.actions?.update ? 
                              <CheckCircleOutlined style={{ color: '#52c41a' }} /> : 
                              <CloseCircleOutlined style={{ color: '#ccc' }} />
                            }
                            编辑功能
                          </Space>
                        </Col>
                        <Col span={8}>
                          <Space>
                            {selectedTable.actions?.delete ? 
                              <CheckCircleOutlined style={{ color: '#52c41a' }} /> : 
                              <CloseCircleOutlined style={{ color: '#ccc' }} />
                            }
                            删除功能
                          </Space>
                        </Col>
                      </Row>
                    </Card>
                  </div>
                </TabPane>
              </Tabs>
            </div>
          </div>
        ) : (
          <div style={{ 
            height: '100%', 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'center' 
          }}>
            <Empty description="请选择一个表格进行配置" />
          </div>
        )}
      </Content>

      {/* 表格配置模态框 */}
      <Modal
        title={editingTable ? '编辑表格' : '新增表格'}
        open={tableModalVisible}
        onOk={handleSaveTable}
        onCancel={() => setTableModalVisible(false)}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="code"
                label="表格编码"
                rules={[
                  { required: true, message: '请输入表格编码' },
                  { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '编码必须以字母开头' }
                ]}
              >
                <Input placeholder="例如：users" disabled={!!editingTable} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="name"
                label="表格名称"
                rules={[{ required: true, message: '请输入表格名称' }]}
              >
                <Input placeholder="例如：用户管理" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="description" label="描述">
            <TextArea rows={2} placeholder="请输入表格描述" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="tableName"
                label="数据表名"
                rules={[{ required: true, message: '请输入数据表名' }]}
              >
                <Input placeholder="例如：users" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="apiPath" label="API路径">
                <Input placeholder="例如：/users" />
              </Form.Item>
            </Col>
          </Row>

          <Divider>功能配置</Divider>
          
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="create" valuePropName="checked" initialValue={true}>
                <Checkbox>新增功能</Checkbox>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="update" valuePropName="checked" initialValue={true}>
                <Checkbox>编辑功能</Checkbox>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="delete" valuePropName="checked" initialValue={true}>
                <Checkbox>删除功能</Checkbox>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="status" valuePropName="checked" initialValue={true}>
                <Checkbox>启用状态</Checkbox>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      {/* 字段配置模态框 */}
      <FieldEditor
        visible={fieldModalVisible}
        field={editingField}
        onSave={handleSaveField}
        onCancel={() => {
          setFieldModalVisible(false);
          setEditingField(null);
        }}
      />
    </Layout>
  );
};

export default TableConfigManagement;
